package com.isoft.util;

import com.isoft.bean.MyMailMessage;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;

@Component
public class MyMailUtil {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    /*发送简单邮件*/
    protected void sendSimpleMail(MyMailMessage mailMessage){
        SimpleMailMessage simpleMailMessage=new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(mailMessage.getTo());
        simpleMailMessage.setSubject(mailMessage.getSubject());
        simpleMailMessage.setText(mailMessage.getText());
        mailSender.send(simpleMailMessage);
    }
    /*发送HTML邮件*/
    public void sendHtmlMail(MyMailMessage message){
        MimeMessagePreparator mimeMessagePreparator=mimeMessage -> {
            MimeMessageHelper helper=new MimeMessageHelper(mimeMessage);
            helper.setFrom(from);
            helper.setTo(message.getTo());
            helper.setSubject(message.getSubject());
            helper.setText(message.getText(),true);
        };
        mailSender.send(mimeMessagePreparator);
    }
    /*发送带有附件邮件*/
    protected void sendAttachementMail(MyMailMessage mailMessage,boolean isHtml){
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper helper=new MimeMessageHelper(mimeMessage);
                helper.setFrom(from);
                helper.setTo(mailMessage.getTo());
                helper.setSubject(mailMessage.getSubject());
                helper.setText(mailMessage.getText(),isHtml);
                if (null != mailMessage.getAttachementFile()){
                    helper.addAttachment(mailMessage.getAttachementFileName(),mailMessage.getAttachementFile());
                }
                if (null != mailMessage.getAttachementSource()){
                    helper.addAttachment(mailMessage.getAttachementFileName(),mailMessage.getAttachementSource());
                }
            }
        };
        mailSender.send(preparator);
    }

}
